#!/usr/bin/env bash

# set -e -o pipefail

_config_set(){
  settings="$(cd /tmp && pwd -W)/$(mktemp -u|sed "s+^/tmp/++").xml"
  echo "<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"
            xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
            xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd\">
    <mirrors>
      <mirror>
        <id>local-repo</id>
        <mirrorOf>*</mirrorOf>
        <url>https://maven.aliyun.com/repository/public</url>
      </mirror>
    </mirrors>
  </settings>
  " > "$settings"
}

_config_clean(){
  rm -rf $settings
}

_mvn(){
  mvn -Duser.home="$(pwd -W)/dist" -s "$settings" $@
}

_mvn_libs(){
  _mvn dependency:tree -B| sed "s/\s*$//g" |\
   grep -o "[^ ]\+\(compile\|runtime\|test\|provided\)$" |\
   sed -e "s/:\(compile\|runtime\|test\|provided\)$//g" \
    -e "s/:jar//g" |sort|uniq
}

download_java(){
  _config_set
  # _mvn_libs > lib.md
  deps=($(_mvn_libs))
  for dep in ${deps[@]}; do
    _mvn dependency:get -Dartifact="$dep"
  done
  _mvn dependency:resolve dependency:resolve-plugins dependency:sources
  _mvn clean install -DskipTests
  _config_clean
}

download_web(){
  yarn --cwd="$1" \
    --cache-folder="$(pwd -W)/dist/yarn_cache" \
    --registry=https://registry.npmmirror.com
}

case $1 in
  download-java) download_java ;;
  download-web) download_web $2 ;;
esac
